package idv.loveloser.mobilemoodle;


import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ActionBar.LayoutParams;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TabHost;

public class CourseManager extends ListActivity {
	private SharedPreferences sets;
	private long client;
	private String sessionKey;
	private boolean hasRight;
	private List<MdlCourse> courses;
	private View bottom_view; 
	private ListView coursesView;
	private Button addMoreBtn,courseManagerAddUrlBtn,courseManagerAddForumBtn;
	private List<CourseContent> contents;
	private long newForumCourseId=-1L;
	private long newUrlCourseId=-1L;
//	private FrameLayout courseContentRoot;
	
	private ListView courseContentListView;
	private long courseId;
	private int sectionCount=-1;
	private long sectionId=-1L;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.courses_manager);
        courseContentListView=(ListView) findViewById(R.id.courseContent);
        try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        courseManagerAddForumBtn=(Button) findViewById(R.id.courseManagerAddForumBtn);
        courseManagerAddForumBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				final Dialog myDialog = new Dialog(CourseManager.this);
				myDialog.setContentView(R.layout.forum_new_forum);
				final EditText newForumName = (EditText) myDialog.findViewById(R.id.newForumName);
				final EditText newForumDescription =(EditText) myDialog.findViewById(R.id.newForumDescription);
				Button addCourseForumBtn=(Button) myDialog.findViewById(R.id.addCourseForumBtn);
				Spinner courseManagerAddNewForumCourseSpinner = (Spinner) myDialog.findViewById(R.id.courseManagerAddNewForumCourseSpinner);
				final Spinner courseManagerAddNewForumSectionSpinner = (Spinner)myDialog.findViewById(R.id.courseManagerAddNewForumSectionSpinner);
				String[] courseSpinnerContent =new String[courses.size()];
				for(int index=0;index<courseSpinnerContent.length;index++){
					MdlCourse course =courses.get(index);
					courseSpinnerContent[index]=course.getFullname();					
				}
				ArrayAdapter<String> courseSpinnerAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,courseSpinnerContent);
				courseManagerAddNewForumCourseSpinner.setAdapter(courseSpinnerAdapter);
				courseManagerAddNewForumCourseSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						newForumCourseId=courses.get(position).getId();
						
						sectionCount=Integer.parseInt(Util.getCourseSectionCount(client, sessionKey, newForumCourseId).trim());
						String courseSectionResponseStr=Util.getCourseSection(client, sessionKey, newForumCourseId);
						Gson gson = new Gson();
						final List<MdlCourseSections> sections=gson.fromJson(courseSectionResponseStr, new TypeToken<List<MdlCourseSections>>(){}.getType()); 
						String[] sectionContent=new String[sections.size()+1];
						sectionContent[0]="Add New Section";
						
						for(int index=1;index<sections.size()+1;index++){
							sectionContent[index]="Section "+index;
						}
						ArrayAdapter<String> sectionAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,sectionContent);
						courseManagerAddNewForumSectionSpinner.setAdapter(sectionAdapter);
						courseManagerAddNewForumSectionSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
							@Override
							public void onItemSelected(AdapterView<?> arg0, View arg1,
									int position, long arg3) {
								if(position!=0){
									MdlCourseSections section = sections.get(position-1);
									sectionId=section.getId();
								
								}
							}

							@Override
							public void onNothingSelected(AdapterView<?> arg0) {
								// TODO Auto-generated method stub
								sectionId=-1L;
							}
						});
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						newForumCourseId=0L;
						sectionCount=Integer.parseInt(Util.getCourseSectionCount(client, sessionKey, newForumCourseId));
						String courseSectionResponseStr=Util.getCourseSection(client, sessionKey, newForumCourseId);
						Gson gson = new Gson();
						final List<MdlCourseSections> sections=gson.fromJson(courseSectionResponseStr, new TypeToken<List<MdlCourseSections>>(){}.getType()); 
						String[] sectionContent=new String[sectionCount+1];
						sectionContent[0]="Add New Section";
						for(int index=1;index<sectionCount;index++){
							sectionContent[index]="Section "+index;
						}
						ArrayAdapter<String> sectionAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,sectionContent);
						courseManagerAddNewForumSectionSpinner.setAdapter(sectionAdapter);
						courseManagerAddNewForumSectionSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
							@Override
							public void onItemSelected(AdapterView<?> arg0, View arg1,
									int position, long arg3) {
								if(position!=0){
									MdlCourseSections section = sections.get(position-1);
									sectionId=section.getId();
								}							
								
							}

							@Override
							public void onNothingSelected(AdapterView<?> arg0) {
								// TODO Auto-generated method stub
								sectionId=-1L;
							}
						});
					}
				});
				addCourseForumBtn.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Util.addForum(client, sessionKey, newForumDescription.getText().toString(), newForumName.getText().toString(), sectionId, courseId);
						myDialog.dismiss();
					}
				});
				myDialog.show();
			}
		});
        courseManagerAddUrlBtn=(Button) findViewById(R.id.courseManagerAddUrlBtn);
        courseManagerAddUrlBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final Dialog myDialog = new Dialog(CourseManager.this);
				myDialog.setContentView(R.layout.forum_new_url);
				final Spinner courseManagerAddNewUrlCourseSpinner=(Spinner) myDialog.findViewById(R.id.courseManagerAddNewUrlCourseSpinner);
				final Spinner courseManagerAddNewUrlSectionSpinner=(Spinner)myDialog.findViewById(R.id.courseManagerAddNewUrlSectionSpinner);
				final EditText newURLName = (EditText) myDialog.findViewById(R.id.newURLName);
				final EditText newURLDescription = (EditText) myDialog.findViewById(R.id.newURLDescription);
				final EditText courseManagerNewUrlEditText=(EditText) myDialog.findViewById(R.id.courseManagerNewUrlEditText);
				Button addCourseUrlBtn =(Button) myDialog.findViewById(R.id.addCourseUrlBtn);
				String[] urlSpinnerContent =new String[courses.size()];
				for(int index=0;index<urlSpinnerContent.length;index++){
					MdlCourse course =courses.get(index);
					urlSpinnerContent[index]=course.getFullname();					
				}
				ArrayAdapter<String> courseSpinnerAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,urlSpinnerContent);
				courseManagerAddNewUrlCourseSpinner.setAdapter(courseSpinnerAdapter);
				courseManagerAddNewUrlCourseSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						newUrlCourseId=courses.get(position).getId();
						sectionCount=Integer.parseInt(Util.getCourseSectionCount(client, sessionKey, newForumCourseId).trim());
						String courseSectionResponseStr=Util.getCourseSection(client, sessionKey, newUrlCourseId);
						Gson gson = new Gson();
						final List<MdlCourseSections> sections=gson.fromJson(courseSectionResponseStr, new TypeToken<List<MdlCourseSections>>(){}.getType()); 
						String[] sectionContent=new String[sectionCount+1];
						sectionContent[0]="Add New Section";
						for(int index=1;index<sectionCount;index++){
							sectionContent[index]="Section "+index;
						}
						ArrayAdapter<String> sectionAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,sectionContent);
						courseManagerAddNewUrlSectionSpinner.setAdapter(sectionAdapter);
						courseManagerAddNewUrlSectionSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

							@Override
							public void onItemSelected(AdapterView<?> arg0,
									View arg1, int position, long arg3) {
								if(position!=0){
									MdlCourseSections section = sections.get(position-1);
									sectionId=section.getId();
								}
							}

							@Override
							public void onNothingSelected(AdapterView<?> arg0) {
								// TODO Auto-generated method stub
								sectionId=-1L;
							}
						});
						
						
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						newUrlCourseId=0L;
						sectionCount=Integer.parseInt(Util.getCourseSectionCount(client, sessionKey, newUrlCourseId));
						String courseSectionResponseStr=Util.getCourseSection(client, sessionKey, newUrlCourseId);
						Gson gson = new Gson();
						final List<MdlCourseSections> sections=gson.fromJson(courseSectionResponseStr, new TypeToken<List<MdlCourseSections>>(){}.getType()); 
						String[] sectionContent=new String[sectionCount+1];
						sectionContent[0]="Add New Section";
						for(int index=1;index<sectionCount;index++){
							sectionContent[index]="Section "+index;
						}
						ArrayAdapter<String> sectionAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,sectionContent);
						courseManagerAddNewUrlSectionSpinner.setAdapter(sectionAdapter);
						courseManagerAddNewUrlSectionSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
							@Override
							public void onItemSelected(AdapterView<?> arg0, View arg1,
									int position, long arg3) {
								if(position!=0){
									MdlCourseSections section = sections.get(position-1);
									sectionId=section.getId();
								}							
								
							}

							@Override
							public void onNothingSelected(AdapterView<?> arg0) {
								// TODO Auto-generated method stub
								sectionId=-1L;
							}
						});
						
					}
				});
				addCourseUrlBtn.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						Util.addCourseUrl(client, sessionKey,sectionId,newUrlCourseId,newURLName.getText().toString(),courseManagerNewUrlEditText.getText().toString(), newURLDescription.getText().toString());
						myDialog.dismiss();
					}
				});
				myDialog.show();
			}
		});
        coursesView=getListView();
        sets=getApplicationContext().getSharedPreferences("MySettings", MODE_WORLD_WRITEABLE );
        client=sets.getLong("client", -1L);
        sessionKey = sets.getString("sessionKey", "");
        hasRight=sets.getBoolean("hasRight", false);
        String allCoursesStr=Util.getAllCourse(client, sessionKey);
        Gson gson=new Gson();
        bottom_view =getLayoutInflater().inflate(R.layout.course_bottom_view, null);
        coursesView.addFooterView(bottom_view);
        addMoreBtn=(Button) bottom_view.findViewById(R.id.bt_load);
        
        addMoreBtn.setOnClickListener(new OnClickListener() {
    		
    		@Override
    		public void onClick(View v) {
    			Intent courseEditorIntent = new Intent(getApplicationContext(),CourseEditor.class);
    			startActivity(courseEditorIntent);
    		}
    	});
        if(hasRight==false){
        	addMoreBtn.setEnabled(false);
        	courseManagerAddUrlBtn.setEnabled(false);
        	courseManagerAddForumBtn.setEnabled(false);
        }
        courses = gson.fromJson(allCoursesStr, new TypeToken<List<MdlCourse>>(){}.getType()); 
        CourseManagerAdapter adapter = new CourseManagerAdapter(getApplicationContext());
        adapter.setCourses(courses);
        setListAdapter(adapter);
        getListView().setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
//				courseContentTabHost =new TabHost(getApplicationContext());
				MdlCourse course=courses.get(position);
				courseId=course.getId();				
				String responseStr=Util.getCourseSection(client, sessionKey, courseId);
		        Gson gson = new Gson();
		        contents = gson.fromJson(responseStr, new TypeToken<List<CourseContent>>(){}.getType());
				CourseContentAdapter courseContentAdapter = new CourseContentAdapter(getApplicationContext());
				courseContentAdapter.setContents(contents);
				courseContentListView.setAdapter(courseContentAdapter);
				courseContentListView.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						long type = contents.get(position).getContentTypeId();
						if(type==7L){//Forum
							Intent postIntent = new Intent(getApplicationContext(),ForumPostsSubjectManager.class);
							postIntent.putExtra("courseId", courseId);
							postIntent.putExtra("forumId",contents.get(position).getContentTypeId() );
							startActivity(postIntent);
						}
						if(type==18L){//Url
							String responseStr=Util.getCourseUrl(client, sessionKey, contents.get(position).getInstanceId());
							Gson gson = new Gson();
							MdlUrl url=gson.fromJson(responseStr, MdlUrl.class);
							Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url.getExternalurl()));
							startActivity(browserIntent); 
						}
					}
				});
			}
		});

    }

}
